<?php

	class cmd_memberPoint extends mdl_memberPoint
	{
		function chgPoint($userId, $nPoint, $sReason, $relatedId=null)
		{
			/* alone */
			parent::chgPoint($userId, $nPoint, $sReason, $relatedId);		//调用父类方法 给下单会员改变积分
			$oMem = $this->system->loadModel('member/member');
			$aMem = $oMem->getFieldById($userId, array('refer_id'));		//根据会员ID取得refer_id
			$oOrder = $this->system->loadModel('trading/order');
			$aOrder = $oOrder->getFieldById($relatedId, array('refer_id'));		//根据订单ID取得refer_id
			//先根据订单的refer_id取得推广链接的会员名
			if (strstr($aOrder['refer_id'],'p'))
			{
				$uname = substr($aOrder['refer_id'],1);
				$mem = $oMem->getMemIdByName($uname);
				if ($mem)
				{
					$userId = $mem[0]['member_id'];		//推广链接的会员ID
				}
			}
			//如果订单表中refer_id不存在,则从会员表中找到refer_id
			elseif (strstr($aMem['refer_id'],'p'))
			{
				$uname = substr($aMem['refer_id'],1);
				$mem = $oMem->getMemIdByName($uname);
				if ($mem)
				{
					$userId = $mem[0]['member_id'];		//推广链接的会员ID
				}
			}
			//如果订单和会员表中refer_id都不存在 返回true
			else return true;

			if ($userId)
			{
				if ($nPoint==0){
					return true;
				}else if(!$this->_chgPoint($userId, $nPoint)) {
					trigger_error(__('积分扣除超过会员已有积分'), E_USER_ERROR);
					return false;
				}

				$aPoint = $oMem->getFieldById($userId, array('point'));
				$oLv = $this->system->loadModel('member/level');
				if ($userId && ($oLv->checkMemLvType($userId) != 'wholesale'))
				{
					$userId = intval($userId);
					$oPointHistory = $this->system->loadModel('trading/pointHistory');
					$aUserPoint['point'] = $this->getMemberPoint($userId);
					$aUserPoint['point'] += $nPoint;

					$rRs = $this->db->query('select * from sdb_members where member_id='.$userId);
					$sSql = $this->db->GetUpdateSQL($rRs, $aUserPoint);
					if($sSql)$this->db->exec($sSql);
					$this->toUpdatelevel($userId);
					$aPointHistory = array(
										'member_id' => $userId,
										'point' => $nPoint,
										'reason' => 'promotion_link_get',
										'related_id' => $relatedId);
					$oPointHistory->addHistory($aPointHistory);
				}
			}

			return true;
		}
	}
?>